package com.jacoco.incremental.utils;


import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * jacoco 命令
 */

public class JacocoCMD {


    private StringBuilder message = new StringBuilder();

    /**
     * 执行命令
     *
     * @param order
     * @return
     * @throws Exception
     */
    public boolean exec(String[] order) throws Exception {
        boolean success = true;
        ProcessBuilder builder = new ProcessBuilder(order);
        builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        p.waitFor();
        if (p.exitValue() != 0) {
            String error = arrayToString(order);
            ViewInfo.error("命令执行失败: {}" + error);
            success = false;
            message.append("命令：" + error + "\n");
        }
        String line = "";
        while ((line = reader.readLine()) != null) {
            message.append(line + "\n");
        }
        System.out.println(message);
        p.destroy();
        return success;
    }

    private String arrayToString(String[] array) {
        if (Empty.isNotEmpty(array)) {
            StringBuilder builder = new StringBuilder();
            for (String t : array) {
                builder.append(t + " ");
            }
            return builder.toString();
        }
        return "";
    }
}
